package com.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipUtil {
	public static void zipFile(String regionFileName, String zipFileName){
		try {
			File regionFile = new File(regionFileName);
			
			ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFileName));
			FileInputStream in = new FileInputStream(regionFile);
			zipOut.putNextEntry(new ZipEntry(regionFile.getName()));
			
			int temp;
			while ((temp = in.read()) != -1) {
				zipOut.write(temp);
			}
			in.close();
			zipOut.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	

	public static void zipFiles(String downloadZipFile, String path, File... srcFiles)
			throws IOException {
		ZipOutputStream out = new ZipOutputStream(new FileOutputStream(downloadZipFile));
		ZipUtil.zipFiles(out, path, srcFiles);
		out.close();
		System.out.println("*****************ѹ�����*******************");
	}


	public static void zipFiles(ZipOutputStream out, String path, File... srcFiles) {
		path = path.replaceAll("\\*", "/");
		if (!path.endsWith("/")) {
			path += "/";
		}
		byte[] buf = new byte[1024];
		try {
			for (int i = 0; i < srcFiles.length; i++) {
				if (srcFiles[i].isDirectory()) {
					File[] files = srcFiles[i].listFiles();
					String srcPath = srcFiles[i].getName();
					srcPath = srcPath.replaceAll("\\*", "/");
					if (!srcPath.endsWith("/")) {
						srcPath += "/";
					}
					out.putNextEntry(new ZipEntry(path + srcPath));
					zipFiles(out, path + srcPath, files);
				} else {
					FileInputStream in = new FileInputStream(srcFiles[i]);
					System.out.println(path + srcFiles[i].getName());
					out.putNextEntry(new ZipEntry(path + srcFiles[i].getName()));
					int len;
					while ((len = in.read(buf)) > 0) {
						out.write(buf, 0, len);
					}
					out.closeEntry();
					in.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	

}
